<?php

namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Models\Tools\Data;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreAppealController extends ClientController
{

    public function index()
    {

        $all = $this->all;
        $work_id = $all['work_id'];
        $appeal_remark = $all['appeal_remark'];

        try {
            DB::beginTransaction();

            // 查询工单信息
            $work = DB::table('explore_work')
                ->where('work_id', '=', $work_id)
                ->lockForUpdate()
                ->first();
            $work = json_decode(json_encode($work), true);

            if ($work['receiver_we_id'] !== $this->we_id) {
                DB::rollBack();
                return $this->setReturnJson(-1,'这个工单不属于您');
            }
            if($work['status'] !== Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE){
                DB::rollBack();
                return $this->setReturnJson(-1,'当前任务的状态已改变，请刷新当前页面');
            }

            // 新建申诉挂起单
            DB::table('explore_hang_up')->insertGetId([
                'work_id'=>$work_id,
                'refuse_reason'=>$work['accept_remark'],
                'refused_at'=>$work['refused_at'],
                'appeal_remark'=>$appeal_remark,
            ]);

            DB::table('explore_work')->where('work_id','=',$work_id)->update([
                'hang_up'=>1, // 修改状态为正在进行申诉
            ]);

            // 记录工单日志
            DB::table('explore_work_log')->insert([
                'work_id'=>$work_id,
                'action'=>Data::DATA_DB_EXPLORE_WORK_ACTION_APPEAL,
                'we_id'=>$this->we_id,
                'remark'=>'达人提交验收申诉，申诉备注：'.$appeal_remark,
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error(ExploreAppealController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '申请失败');
        }
        DB::commit();
        return $this->setReturnJson(0, '申诉成功，请等待客服评判，申诉结果将为您推送微信模板消息，请注意查看。');

    }

}
